package com.yunshipei.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.common.Globals;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.DrawableUtils;

import org.json.JSONObject;

import java.util.Date;
import java.util.Timer;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by cike on 15/12/23.
 */
public class AuthCodeGetedAcitivity extends FindPaasswardBaseActivity implements View.OnClickListener {
    private View view = null;
    private EditText phoneEdit, authCode;
    private TextView getAuth;
    private static int sTime = 79;
    private Timer timer;
    private AtomicInteger startTime = new AtomicInteger(sTime);
    private boolean authcodeStatus = true;
    private Dialog mDialog = null;
    private String code = "";
    private String uuid = "";
    private Thread myThread = null;
    private SharedPreferences sharedPreferences = null;
    private SharedPreferences.Editor editor = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        view = layoutInflater.inflate(R.layout.auth_code_get, null);
        super.addContentView(view);
        super.setFindPassStatusColor(2);
        sharedPreferences = YspPreferences.getInstance().getSharedPreferences();
        editor = sharedPreferences.edit();
        timer = new Timer();
        initView();
    }

    private Drawable drawable;

    private void initView() {
        Intent intent = getIntent();
        String phone = intent.getBundleExtra("data").getString("phone");
        uuid = intent.getBundleExtra("data").getString("uuid");
        phoneEdit = (EditText) view.findViewById(R.id.input_phone_nember);
        phoneEdit.setFocusableInTouchMode(false);
        authCode = (EditText) view.findViewById(R.id.auth_code);
        next.setAlpha(0.6f);
        next.setEnabled(false);
        authCode.addTextChangedListener(new EditTextWatcher(authCode));
        int color = EnterConfig.getInstance().getGlobalColor();
        drawable = DrawableUtils.newRadioDrawable(0, BaseUtil.dip2px(this, 3), color, color);
        getAuth = (TextView) view.findViewById(R.id.get_auth_code);
        getAuth.setBackgroundDrawable(drawable);
        getAuth.setOnClickListener(this);
        phoneEdit.setText(phone);
    }

    @Override
    public void onClick(View v) {
        String phoneOrmail = phoneEdit.getText().toString();
        if (!TextUtils.isEmpty(phoneOrmail)) {
            getAuth.setAlpha(0.6f);
            getAuth.setClickable(false);
            getAuth.setText("获取验证码");
            startTiming();
            HttpMethods.getInstance().fetchReCaptcha(uuid, phoneOrmail, new EnterBaseSubscriber() {

                @Override
                public void onSuccess(JSONObject data) {
                    code = data.optString("code");
                    Date codeTime = new Date();
                    editor.putString(Globals.AUTHCODETIME, String.valueOf(codeTime.getTime()));
                    editor.putString(Globals.AUTHCODE, code);
                    editor.commit();
                }

                @Override
                public void onFailure(String errorMsg) {
                    AuthCodeGetedAcitivity.super.showToast("获取失败,请重新获取");
                    resumeStatus();
                }
            });
        } else {
            super.showToast("手机或邮箱不能为空");
        }
    }

    public void startTiming() {
        myThread = new Thread(new myRunnable());
        myThread.start();
    }

    public class myRunnable implements Runnable {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(1000);
                    mHandler.sendEmptyMessage(startTime.getAndDecrement());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    Handler mHandler = new Handler() {

        public void handleMessage(Message mas) {
            int timeStr = mas.what;
//            System.out.println("我是定时器" + timeStr);
            if (timeStr > 0) {
                getAuth.setText(timeStr + "s后重新获取");
            } else if (timeStr <= 0) {
                myThread.interrupt();
                resumeStatus();
            }
        }
    };

    public void resumeStatus() {
        getAuth.setText("获取验证码");
        getAuth.setClickable(true);
        getAuth.setBackgroundDrawable(drawable);
        getAuth.setAlpha(1f);
        startTime = new AtomicInteger(sTime);
        code = null;
        authcodeStatus = false;
    }


    @Override
    public void nextClickListener() {
        code = sharedPreferences.getString(Globals.AUTHCODE, "");
        long codeTime = Long.parseLong(sharedPreferences.getString(Globals.AUTHCODETIME, "0"));
        long nowTime = new Date().getTime();
        String inputCode = authCode.getText().toString();
        if (!TextUtils.isEmpty(inputCode) && !TextUtils.isEmpty(code) && inputCode.equals(BaseUtil.makeAuthString(code))) {
            if ((Math.abs(nowTime - codeTime)) <= 5 * 60 * 1000) {
                Intent intent = new Intent();
                intent.putExtra("uuid", uuid);
                intent.setClass(AuthCodeGetedAcitivity.this, SetNewPasswardActivity.class);
//                startActivity(intent);
                startActivityForResult(intent, 2);
//                finish();
            } else {
                super.showToast(getResources().getString(R.string.auth_code_overtime_message));
            }
        } else if (TextUtils.isEmpty(inputCode)) {
            super.showToast(getResources().getString(R.string.auth_code_status_error));
        } else {
            super.showToast(getResources().getString(R.string.auth_code_status_other));
        }
    }

    @Override
    public void onNetworkSuccess(JSONObject jsonObject, String msg) {

    }

    @Override
    public void onNetworkFailure(String errorMsg) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == 1) {
            setResult(1);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myThread != null && !myThread.isInterrupted()) {
            myThread.interrupt();
        }
    }
}
